#!/bin/bash

# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[0;33m'
BLUE='\033[0;34m'
NC='\033[0m' # 没有颜色

# 定义配置文件路径
CONFIG_FILE="/root/.gitsync_config"

# 默认配置
# DEFAULT_NAME="gitSync脚本"
# DEFAULT_EMAIL="default_email@example.com"
# DEFAULT_REPO_PATH="$HOME/我的仓库"
# DEFAULT_REMOTE_URL="git@github.com:你的用户名/你的仓库.git"
# DEFAULT_SSH_COMMENT="gitSync脚本"

# 获取公网IP
PUBLIC_IP=$(curl -s http://ipinfo.io/ip)

function show_banner() {
    echo -e "\e[34m" # Blue color for this banner
    cat << "EOF"
        _ _   ____                   
   __ _(_) |_/ ___| _   _ _ __   ___ 
  / _` | | __\___ \| | | | '_ \ / __|
 | (_| | | |_ ___) | |_| | | | | (__ 
  \__, |_|\__|____/ \__, |_| |_|\___|
  |___/             |___/            
EOF
    echo -e "\e[0m" # Reset to default terminal color
	echo -e "${YELLOW}        作者: 刘登辉${NC}"
    echo -e "${RED}    数据无价，请及时备份！！！${NC}"
}



# 加载配置或初始化配置
function load_or_initialize_config() {
    if [ -f "$CONFIG_FILE" ]; then
        source "$CONFIG_FILE"
    else
        echo "DEFAULT_NAME='gitee'" > "$CONFIG_FILE"
        echo "DEFAULT_EMAIL='default_email@example.com'" >> "$CONFIG_FILE"
        echo "DEFAULT_REPO_PATH='/www/backup/database/mysql/crontab_backup'" >> "$CONFIG_FILE"
        echo "DEFAULT_REMOTE_URL='git@github.com:你的用户名/你的仓库.git'" >> "$CONFIG_FILE"
        echo "DEFAULT_SSH_COMMENT='gitSync脚本'" >> "$CONFIG_FILE"
		echo "DEFAULT_BRANCH_NAME='$PUBLIC_IP'" >> "$CONFIG_FILE"
        source "$CONFIG_FILE"
    fi
}
# 更新配置文件
function update_config_file() {
    echo "DEFAULT_NAME='$DEFAULT_NAME'" > "$CONFIG_FILE"
    echo "DEFAULT_EMAIL='$DEFAULT_EMAIL'" >> "$CONFIG_FILE"
    echo "DEFAULT_REPO_PATH='$DEFAULT_REPO_PATH'" >> "$CONFIG_FILE"
    echo "DEFAULT_REMOTE_URL='$DEFAULT_REMOTE_URL'" >> "$CONFIG_FILE"
    echo "DEFAULT_SSH_COMMENT='$DEFAULT_SSH_COMMENT'" >> "$CONFIG_FILE"
	echo "DEFAULT_BRANCH_NAME='$DEFAULT_BRANCH_NAME'" >> "$CONFIG_FILE"
}




# 显示帮助信息
function show_help() {
    echo -e "${YELLOW}使用方法: gitSync [选项]${NC}"
    echo -e "${YELLOW}选项:${NC}"
    echo -e "  ${GREEN}-run  从头开始自动执行所有配置步骤${NC}"
    echo -e "  ${GREEN}-menu 显示菜单，手动选择要执行的配置步骤${NC}"
	echo -e "  ${GREEN}-push 推送至Gitee${NC}"
    echo -e "  ${GREEN}-help 显示帮助信息${NC}"
    echo -e "${YELLOW}默认配置：${NC}"
    echo -e "  用户名: ${BLUE}$DEFAULT_NAME${NC}"
    echo -e "  邮箱: ${BLUE}$DEFAULT_EMAIL${NC}"
    echo -e "  本地仓库路径: ${BLUE}$DEFAULT_REPO_PATH${NC}"
    echo -e "  远程仓库URL: ${BLUE}$DEFAULT_REMOTE_URL${NC}"
	echo -e "  设置本服务器仓库分支: ${BLUE}$DEFAULT_BRANCH_NAME${NC}"
}

# 菜单系统
function show_menu() {
    echo -e "${GREEN}1) 设置Git用户名和邮箱${NC}"
    echo -e "${GREEN}2) 设置SSH密钥备注${NC}"
    echo -e "${GREEN}3) 设置本地Git仓库路径${NC}"
    echo -e "${GREEN}4) 设置远程Git仓库URL${NC}"
	echo -e "${GREEN}5) 设置本服务器仓库分支${NC}"
    echo -e "${GREEN}6) git内容推送仓库${NC}"
	echo -e "${GREEN}7) 查看SSH公钥${NC}"
	echo -e "${GREEN}8) 修改默认变量${NC}"
    echo -e "${RED}9) 退出${NC}"
}

#1. 设置Git用户名和邮箱
function set_git_config() {
    echo -e "当前用户名: ${BLUE}$(git config --global user.name)${NC}"
    echo -e "当前邮箱: ${BLUE}$(git config --global user.email)${NC}"
    read -e -p "是否设置自定义Git用户名？(y/n): " yn
    if [[ $yn == "y" ]]; then
        read -e -p "输入Git用户名: " name
        git config --global user.name "$name"
		DEFAULT_NAME="$name"
		update_config_file
    else
        git config --global user.name "$DEFAULT_NAME"
    fi

    read -e -p "是否设置自定义Git邮箱？(y/n): " yn
    if [[ $yn == "y" ]]; then
        read -e -p "输入Git邮箱: " email
        git config --global user.email "$email"
		DEFAULT_EMAIL="$email"
		update_config_file
    else
        git config --global user.email "$DEFAULT_EMAIL"
    fi
}

#2. 设置SSH key备注
function set_ssh_comment() {
    local ssh_key_path="$HOME/.ssh/id_rsa"
    local ssh_pub_key_path="$ssh_key_path.pub"

    if [[ -f "$ssh_pub_key_path" ]]; then
        echo -e "${GREEN}已存在SSH密钥，跳过生成步骤。${NC}"
        echo -e "这是你的公钥,请在Gitee上面进行设置:"
        echo -e "\e[32m$(cat "$ssh_pub_key_path")\e[0m"
		# 读取公钥文件并提取 == 后的内容
        local pubkey_content=$(cat "$ssh_pub_key_path")
        local pubkey_comment=${pubkey_content#*== }
        
        echo -e "公钥备注信息: ${BLUE}$pubkey_comment${NC}"
        
        DEFAULT_SSH_COMMENT="$pubkey_comment"
		update_config_file
    else
        echo -e "你的公网IP是: ${BLUE}$PUBLIC_IP${NC}"
        read -e -p "输入SSH密钥备注: " comment
        ssh_key_comment="$comment [$PUBLIC_IP]"
		# 保存备注到全局变量
		DEFAULT_SSH_COMMENT="$ssh_key_comment"
		update_config_file
        ssh-keygen -t rsa -b 4096 -C "$ssh_key_comment" -f "$ssh_key_path"
        echo -e "SSH密钥已生成，备注为: $ssh_key_comment"
        echo -e "这是你的公钥:"
		echo -e "\e[34m$($ssh_pub_key_path)\e[0m"

    fi

    read -e -p "你已经复制了密钥吗？(y/n): " copied
    if [[ $copied == "y" ]]; then
		echo -e "${GREEN}Gitee连接检测结果...${NC}"
        # 检测Gitee连接
        ssh_output=$(ssh -T git@gitee.com)
        echo -e "$ssh_output"
	else
		echo -e "${GREEN}Gitee连接检测结果...${NC}"
        # 检测Gitee连接
        ssh_output=$(ssh -T git@gitee.com)
        echo -e "$ssh_output"
    fi
}



# 3.设置Git仓库路径
function set_repo_path() {
    echo -e "默认的本地仓库路径是: ${BLUE}$DEFAULT_REPO_PATH${NC}"
    read -e -p "输入本地Git仓库路径（或按Enter使用默认路径）: " path
    if [[ -z $path ]]; then
        path=$DEFAULT_REPO_PATH
    else
        DEFAULT_REPO_PATH=$path  # 更新全局变量
    fi
    git init "$path"
    pushd "$path"  # 保存当前目录并更改到新目录
    git add .
    git commit -m "$DEFAULT_SSH_COMMENT-初始提交"
    popd  # 返回原目录
    update_config_file
}


#4. 设置仓库推送地址
function set_remote_url() {
    echo -e "默认的远程仓库URL是: ${BLUE}$DEFAULT_REMOTE_URL${NC}"
    read -e -p "输入Git远程仓库URL（或按Enter使用默认URL）: " url
    if [[ -z $url ]]; then
        url=$DEFAULT_REMOTE_URL
    else
        DEFAULT_REMOTE_URL=$url  # 更新全局变量
    fi
    pushd "$DEFAULT_REPO_PATH"
    if git remote | grep -q 'origin'; then
        git remote set-url origin "$url"
    else
        git remote add origin "$url"
    fi
    popd
    update_config_file
}


function create_git_branch_name() {
    local input="$1"
    # 使用 tr 删除特殊字符和替换空格为下划线
    local sanitized=$(echo "$input" | tr -d ' ~^:?\[\]*' | tr ' ' '_')

    # 剔除不允许的开头字符
    sanitized=$(echo "$sanitized" | sed -e 's/^[./]//')

    # 剔除.lock结尾
    sanitized=$(echo "$sanitized" | sed -e 's/\.lock$//')

    # 检查是否为 Git 保留名称
    case "$sanitized" in
        HEAD|FETCH_HEAD|ORIG_HEAD|MERGE_HEAD)
            sanitized="${sanitized}_branch"
            ;;
    esac

    # 确保生成的分支名称不为空
    if [ -z "$sanitized" ]; then
        sanitized="default_branch"
    fi

    echo "$sanitized"
}

#5. 用户输入并创建分支的函数
function create_branch_from_user_input() {
    echo "请输入您想创建的分支名称："
    read -r branch_input

    local branch_name=$(create_git_branch_name "$branch_input")
    echo "格式化后的分支名为：$branch_name"

    # 确认是否创建分支
    read -p "是否要创建此分支？(y/n): " confirm
    if [[ "$confirm" == "y" ]]; then
        # Git 操作
        if git rev-parse --verify --quiet "$branch_name"; then
			echo "$branch_name 分支已存在，切换到该分支。"
			git checkout "$branch_name"
		else
			echo "分支不存在，创建并切换到新分支。"
			git checkout -b "$branch_name"
		fi
		DEFAULT_BRANCH_NAME="$branch_name"
		update_config_file
        echo "分支 $branch_name 已创建并切换。"
    else
        echo "操作取消。"
    fi
}



#6. git推送
function set_push() {
    pushd "$DEFAULT_REPO_PATH" || return  # 安全地改变目录
	if git rev-parse --verify --quiet "$DEFAULT_BRANCH_NAME"; then
		echo "$DEFAULT_BRANCH_NAME 分支已存在，切换到该分支。"
		git checkout "$DEFAULT_BRANCH_NAME"
	else
		echo "分支不存在，创建并切换到新分支。"
		git checkout -b "$DEFAULT_BRANCH_NAME"
	fi
		
    git add --all

    # 获取当前日期和时间
    CURRENT_DATETIME="$(date '+%Y-%m-%d %H:%M:%S')"
    echo -e "当前推送的Comment: ${BLUE}$DEFAULT_SSH_COMMENT-$CURRENT_DATETIME${NC}"


    # 执行git commit
    git commit -m "gitSync脚本推送: $DEFAULT_SSH_COMMENT-$CURRENT_DATETIME"

    # 检查是否已设置远程仓库URL
    if git remote | grep -q origin; then
        echo -e "${GREEN}已存在远程URL，直接推送。${NC}"
    else
        echo -e "${RED}未设置远程URL，推送失败。${NC}"
        popd
        return 1 # 返回非0状态表示失败
    fi

    # 执行git push
    git push -u origin "$DEFAULT_BRANCH_NAME"
    popd
}

# 7.查看SSH公钥
function view_ssh_key() {
    echo -e "${YELLOW}这是你的SSH公钥:${NC}"
    if [ -f ~/.ssh/id_rsa.pub ]; then
        echo -e "\e[34m$(cat ~/.ssh/id_rsa.pub)\e[0m"
    else
        echo -e "${RED}未找到公钥文件！请先生成SSH密钥。${NC}"
    fi
}



# 显示和处理全局变量修改的二级菜单
function modify_variables_menu() {
    while true; do
        echo -e "${YELLOW}选择要修改的变量:${NC}"
        echo -e "1) 修改默认用户名 (当前值: ${BLUE}$DEFAULT_NAME${NC})"
        echo -e "2) 修改默认邮箱 (当前值: ${BLUE}$DEFAULT_EMAIL${NC})"
        echo -e "3) 修改默认仓库路径 (当前值: ${BLUE}$DEFAULT_REPO_PATH${NC})"
        echo -e "4) 修改默认远程URL (当前值: ${BLUE}$DEFAULT_REMOTE_URL${NC})"
        echo -e "5) 修改默认SSH备注 (当前值: ${BLUE}$DEFAULT_SSH_COMMENT${NC})"
		echo -e "6) 修改分支并切换【修改分支会删除旧分支】 (当前值: ${BLUE}$DEFAULT_BRANCH_NAME${NC})"
        echo -e "7) 退出"
        read -e -p "请输入选项: " var_option
        case $var_option in
            1) 
                read -e -p "输入新的默认用户名: " DEFAULT_NAME
                echo -e "${GREEN}默认用户名已更新为: $DEFAULT_NAME${NC}"
                update_config_file
				break ;;
            2) 
                read -e -p "输入新的默认邮箱: " DEFAULT_EMAIL
                echo -e "${GREEN}默认邮箱已更新为: $DEFAULT_EMAIL${NC}"
                update_config_file
				break ;;
            3) 
                read -e -p "输入新的仓库路径: " DEFAULT_REPO_PATH
                echo -e "${GREEN}默认仓库路径已更新为: $DEFAULT_REPO_PATH${NC}"
                update_config_file
				break ;;
            4) 
                read -e -p "输入新的远程URL: " DEFAULT_REMOTE_URL
                echo -e "${GREEN}默认远程URL已更新为: $DEFAULT_REMOTE_URL${NC}"
                update_config_file
				break ;;
            5) 
                read -e -p "输入新的SSH备注: " DEFAULT_SSH_COMMENT
                echo -e "${GREEN}默认SSH备注已更新为: $DEFAULT_SSH_COMMENT${NC}"
                update_config_file
				break ;;
			6) 
                read -e -p "输入新的分支名称: " DEFAULT_BRANCH_NAME
                echo -e "${GREEN}分支名称已更新为: $DEFAULT_BRANCH_NAME${NC}"
				create_branch_from_user_input
				update_config_file
				break ;;

            7) break ;;
            *) echo -e "${RED}无效选项，请重新输入。${NC}" ;;
        esac
    done
}


# 自动执行全部步骤
function run_all_steps() {
    set_git_config
    set_ssh_comment
    set_repo_path
    set_remote_url
	create_branch_from_user_input
    set_push
	update_config_file  # 确保执行完 run 后保存所有更改
}

# 主程序
function main() {
	show_banner
	load_or_initialize_config
    if [[ $1 == "-run" ]]; then
        run_all_steps
    elif [[ $1 == "-menu" ]]; then
        while true; do
            show_menu
            read -e -p "选择一个选项: " option
            case $option in
                1) set_git_config 
					break ;;
                2) set_ssh_comment 
					break ;;
                3) set_repo_path 
					break ;;
                4) set_remote_url 
					break ;;
				5) create_branch_from_user_input 
					break ;;
                6) set_push 
					break ;;
				7) view_ssh_key 
					break ;;
				8) modify_variables_menu 
					break ;;
                9) break ;;
                *) echo -e "${RED}无效选项。${NC}" ;;
            esac
        done
	elif [[ $1 == "-push" ]]; then
		set_push
    elif [[ $1 == "-help" ]] || [[ -z $1 ]]; then
        show_help
    else
        echo -e "${RED}未知的选项。请使用 -help 查看帮助信息。${NC}"
    fi
}

main $1
